package com.gzz.orchid.common.core.support;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 按时间戳生成序列号
 *
 * @author higmd
 */
public abstract class SerialNoWorker {
    //设置开始时间
    private static final long BEGIN_TIME = 1735689600L;
    //序列号的位数
    private static final int COUNT_BITS = 32;
    private final StringRedisTemplate stringRedisTemplate;

    public SerialNoWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIME;
        // 生成序列号
        // 获取当前日期，精确到天
        String date = now.format(getFormatter());
        // 自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        // 拼接
        return timestamp << COUNT_BITS | count;
    }

    /**
     * 格式化日期
     * 子类重写即可获取不同的日期序列号
     *
     * @return
     */
    public DateTimeFormatter getFormatter() {
        return DateTimeFormatter.ofPattern("yyyy:MM:dd");
    }
}
